# This script will run all code for "How the Wealth was Won" by Greenwald,
# Lettau, and Ludvigson, in conjunction with the replication package. Please be
# advised that to fit everything into a single script, we are running the
# estimation in serial rather than in parallel, which is a major slowdown. See
# README and the companion script run_chain.sh for more details.

# This function makes sure we unset all the run instructions between runs
function unset_all() {
    export GLL_RECOMPUTE_DATA=0
    export GLL_ESTIMATE_RWMC=0
    export GLL_FIND_MODE=0
    export GLL_COMPUTE_HESSIAN=0
    export GLL_SAMPLE_RWMC=0
    export GLL_DRAW_STATES_RWMC=0
    export GLL_SIMULATE_RWMC=0
    export GLL_FITTED_VALUES_RWMC=0
    export GLL_MISC_RWMC=0
    export GLL_RWMC_COUNTERFACTUALS=0
    export GLL_RWMC_BOND_PRICING=0
    export GLL_RESULTS=0
    unset GLL_MCMC_CHAIN
}

pushd code

# Motivating plots 
python data_only_plots.py

# Set spec number
spec=49
export GLL_SPEC_NO=$spec

# Estimation Step 1: Construct the data set
unset_all
export GLL_RECOMPUTE_DATA=1
python main.py

# Estimation Step 2: Estimate the model using Sequential Monte Carlo
unset_all
export GLL_ESTIMATE_SMC=1
python main.py

# Estimation Step 3: Compute the maximum likelihood estimate and Hessian
unset_all
export GLL_FIND_MODE=1
export GLL_COMPUTE_HESSIAN=1
python main.py

# Estimation Step 4: Main RWMC estimation step.
#
# Note: this step as written will run all chains in serial. To save time, we
# strongly recommend running this step in separate runs each with a unique
# chain_no using the companion script run_chain.sh

unset_all
export GLL_SAMPLE_RWMC=1
export GLL_DRAW_STATES_RWMC=1
export GLL_SIMULATE_RWMC=1
export GLL_FITTED_VALUES_RWMC=1
export GLL_MISC_RWMC=1
for chain_no in {0..9}; do
    export GLL_MCMC_CHAIN=$chain_no
    python main.py
done

# Estimation Step 5: Additional computations
unset_all
export GLL_RWMC_COUNTERFACTUALS=1
export GLL_RWMC_BOND_PRICING=1
python main.py

# Estimation Step 6: Main output (tables and figures) for the paper
unset_all
export GLL_RESULTS=1
python main.py

# Additional plots
python other_plots.py

# Collect tables and figures
bash collect_tables_and_figures.sh

popd
